﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace HeThongDAO
{
    public class SqlDataAccessHelper : DataAccessHelper
    {
        public SqlDataAccessHelper()
        {
            strConnection = @"Data Source=(local)\SQLEXPRESS2005;Initial Catalog=QuanLyNhaSachSQL;User Id=sa;Password=123456;"; 
        }

        public override DataTable ExecuteQuery(string strQuery)
        {
            DataTable resTable = new DataTable();

            SqlConnection _con = new SqlConnection(strConnection);
            try
            {
                _con.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(strQuery, _con);
                adapter.Fill(resTable);
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }

            return resTable;
        }

        public override void ExecuteNonQuery(string strQuery)
        {
            SqlConnection _con = new SqlConnection(strConnection);

            try
            {
                _con.Open();
                SqlCommand command = _con.CreateCommand();
                command.CommandText = strQuery;
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }
        }

        public override DataTable ExecuteProcedure(string storeProcName, Dictionary<string, object> para)
        {
            DataTable resTable = new DataTable();
            SqlConnection _con = new SqlConnection(strConnection);
            try
            {
                _con.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = _con;
                cmd.CommandText = storeProcName;
                cmd.CommandType = CommandType.StoredProcedure;

                foreach (KeyValuePair<string, object> pair in para)
                {
                    SqlParameter sqlParam = new SqlParameter(pair.Key, pair.Value);
                    cmd.Parameters.Add(sqlParam);
                }

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(resTable);

                _con.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi store procedure: " + ex.Message);
            }

            return resTable;
        }
    }
}
